<template>
  <div class="p-4">
    <!-- 页面标题 -->
    <div class="mb-6">
      <h1 class="text-2xl font-bold text-gray-900">充值管理 MVP</h1>
      <p class="text-gray-600 mt-1">管理充值申请和银行明细匹配</p>
    </div>

    <!-- 统计卡片 -->
    <div class="mb-6 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-4">
      <Card
        v-for="card in statisticCards"
        :key="card.title"
        class="w-full shadow-sm"
        :body-style="{ padding: '16px' }"
      >
        <div class="flex flex-col">
          <span class="text-sm text-gray-500">{{ card.title }}</span>
          <span :class="['mt-2 text-2xl font-semibold', card.color]">
            {{ card.value }}
          </span>
        </div>
      </Card>
    </div>

    <!-- 搜索和列表区域 -->
    <Card>
      <!-- 操作区域 -->
      <div class="mb-6">
        <div class="flex flex-wrap gap-4 items-center justify-between">
          <div class="flex flex-wrap gap-4 items-center">
            <!-- 状态筛选 -->
            <div>
              <label class="text-sm text-gray-600 mr-2">状态:</label>
              <Select
                v-model:value="filters.status"
                @change="fetchRecharges"
                style="width: 120px"
                placeholder="全部"
              >
                <Select.Option value="">全部</Select.Option>
                <Select.Option value="待处理">待处理</Select.Option>
                <Select.Option value="处理中">处理中</Select.Option>
                <Select.Option value="已匹配">已匹配</Select.Option>
                <Select.Option value="已确认">已确认</Select.Option>
              </Select>
            </div>

            <!-- 搜索 -->
            <div>
              <Input
                v-model:value="filters.search"
                @press-enter="fetchRecharges"
                placeholder="搜索充值单号、租户名称或落地公司..."
                style="width: 200px"
              />
            </div>

            <Button type="primary" @click="fetchRecharges">
              搜索
            </Button>
          </div>

          <div class="flex gap-2">
            <Button
              type="primary"
              :loading="matchingLoading"
              @click="runMatching"
            >
              {{ matchingLoading ? '匹配中...' : '执行匹配算法' }}
            </Button>

            <Button @click="fetchRecharges">
              刷新
            </Button>
          </div>
        </div>
      </div>

      <!-- 充值列表 -->
      <div>
        <div class="mb-4">
          <h3 class="text-lg font-semibold">充值申请列表</h3>
        </div>

        <Spin :spinning="loading">
          <Table
            :columns="columns"
            :data-source="recharges"
            :pagination="{
              current: pagination.current_page,
              pageSize: pagination.per_page,
              total: pagination.total,
              showSizeChanger: false,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`
            }"
            @change="handleTableChange"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'recharge_number'">
                <span class="text-blue-600 font-medium">{{ record.recharge_number }}</span>
              </template>
              <template v-if="column.key === 'tenant_name'">
                {{ record.tenant_name || '未填写' }}
              </template>
              <template v-if="column.key === 'amount'">
                <span class="font-medium">¥{{ record.amount }}</span>
              </template>
              <template v-if="column.key === 'status'">
                <Tag :color="getStatusColor(record.status)">
                  {{ getStatusText(record.status) }}
                </Tag>
              </template>
              <template v-if="column.key === 'created_at'">
                {{ formatDate(record.created_at) }}
              </template>
              <template v-if="column.key === 'action'">
                <Space>
                  <Button type="link" size="small" @click="viewDetail(record)">
                    查看详情
                  </Button>
                  <Button
                    v-if="record.status === '已匹配'"
                    type="link"
                    size="small"
                    @click="confirmMatch(record.id)"
                  >
                    确认匹配
                  </Button>
                </Space>
              </template>
            </template>
          </Table>
        </Spin>
      </div>
    </Card>

    <!-- 详情模态框 -->
    <Modal
      v-model:open="showDetail"
      title="充值详情"
      width="720px"
      :footer="null"
      destroyOnClose
      @afterClose="handleDetailAfterClose"
    >
      <div v-if="selectedRecharge" class="max-h-[480px] space-y-4 overflow-y-auto">
        <div class="grid grid-cols-2 gap-4 text-sm">
          <div>
            <span class="text-gray-600">充值单号:</span>
            <span class="ml-2 font-medium">{{ selectedRecharge.recharge_number }}</span>
          </div>
          <div>
            <span class="text-gray-600">金额:</span>
            <span class="ml-2 font-medium">¥{{ selectedRecharge.amount }}</span>
          </div>
          <div>
            <span class="text-gray-600">状态:</span>
            <span class="ml-2" :class="getStatusClass(selectedRecharge.status)">
              {{ getStatusText(selectedRecharge.status) }}
            </span>
          </div>
          <div>
            <span class="text-gray-600">落地公司:</span>
            <span class="ml-2">{{ selectedRecharge.landing_company }}</span>
          </div>
          <div>
            <span class="text-gray-600">租户名称:</span>
            <span class="ml-2">{{ selectedRecharge.tenant_name || '未填写' }}</span>
          </div>
          <div>
            <span class="text-gray-600">银行名称:</span>
            <span class="ml-2">{{ selectedRecharge.bank_name || '未填写' }}</span>
          </div>
          <div>
            <span class="text-gray-600">银行账号:</span>
            <span class="ml-2">{{ selectedRecharge.bank_account || '未填写' }}</span>
          </div>
          <div class="col-span-2">
            <span class="text-gray-600">备注:</span>
            <span class="ml-2">{{ selectedRecharge.remarks || '无' }}</span>
          </div>
        </div>

        <!-- 匹配建议 -->
        <div v-if="matchSuggestions.length > 0" class="border-t pt-4">
          <h4 class="font-medium mb-2">匹配建议:</h4>
          <div class="space-y-2">
            <div
              v-for="suggestion in matchSuggestions"
              :key="suggestion.bank_detail.id"
              class="border rounded p-3 hover:bg-gray-50"
            >
              <div class="flex justify-between items-center">
                <div class="text-sm">
                  <div>流水号: {{ suggestion.bank_detail.serial_no }}</div>
                  <div>金额: ¥{{ suggestion.bank_detail.amt }}</div>
                  <div>置信度: {{ Math.round(suggestion.confidence * 100) }}%</div>
                </div>
                <Button
                  type="primary"
                  size="small"
                  @click="confirmMatchDetail(selectedRecharge.id, suggestion.bank_detail.id)"
                >
                  确认匹配
                </Button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import {
  getRechargeListApi,
  getRechargeDetailApi,
  runMatchingApi,
  confirmMatchApi,
  type FinanceApi
} from '#/api/core/finance'
import { Button, Card, Input, Select, Table, Tag, Spin, Space, Modal, message } from 'ant-design-vue'

// 数据定义
const loading = ref(false)
const matchingLoading = ref(false)
const showDetail = ref(false)
const selectedRecharge = ref<FinanceApi.RechargeRecord | null>(null)
const matchSuggestions = ref<FinanceApi.MatchSuggestion[]>([])

const recharges = ref<FinanceApi.RechargeRecord[]>([])
const pagination = reactive({
  current_page: 1,
  per_page: 20,
  total: 0,
  last_page: 1
})

const statistics = reactive({
  totalRecharges: 0,
  pendingCount: 0,
  matchedCount: 0,
  todayCount: 0
})

const formatNumber = (value: number) => new Intl.NumberFormat('zh-CN').format(value || 0)

const statisticCards = computed(() => [
  {
    title: '总充值申请',
    value: formatNumber(statistics.totalRecharges),
    color: 'text-blue-600'
  },
  {
    title: '待处理',
    value: formatNumber(statistics.pendingCount),
    color: 'text-orange-500'
  },
  {
    title: '已匹配',
    value: formatNumber(statistics.matchedCount),
    color: 'text-green-600'
  },
  {
    title: '今日新增',
    value: formatNumber(statistics.todayCount),
    color: 'text-purple-600'
  }
])

const filters = reactive({
  status: '' as FinanceApi.RechargeListParams['status'] | '',
  search: '',
  page: 1
})

// 表格列配置
const columns = [
  {
    title: '充值单号',
    dataIndex: 'recharge_number',
    key: 'recharge_number',
  },
  {
    title: '租户名称',
    dataIndex: 'tenant_name',
    key: 'tenant_name',
  },
  {
    title: '金额',
    dataIndex: 'amount',
    key: 'amount',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '落地公司',
    dataIndex: 'landing_company',
    key: 'landing_company',
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 辅助函数
const getStatusText = (status: string) => status || '未知状态'

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    '待处理': 'default',
    '处理中': 'processing',
    '已匹配': 'blue',
    '已确认': 'success',
    '失败': 'error',
    '已取消': 'default'
  }
  return colorMap[status] || 'default'
}

const getStatusClass = (status: string) => {
  const classMap: Record<string, string> = {
    '待处理': 'bg-gray-100 text-gray-800',
    '处理中': 'bg-yellow-100 text-yellow-800',
    '已匹配': 'bg-blue-100 text-blue-800',
    '已确认': 'bg-green-100 text-green-800',
    '失败': 'bg-red-100 text-red-800',
    '已取消': 'bg-gray-100 text-gray-800'
  }
  return classMap[status] || 'bg-gray-100 text-gray-800'
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// API 调用函数
const fetchRecharges = async () => {
  loading.value = true
  try {
    const params: FinanceApi.RechargeListParams = {
      page: filters.page,
      per_page: pagination.per_page
    }

    if (filters.status) params.status = filters.status
    if (filters.search) params.search = filters.search

    const response = await getRechargeListApi(params)

    const normalizedList: FinanceApi.RechargeRecord[] = response.list.map((item) => ({
      ...item,
      amount: Number(item.amount ?? 0),
      tenant_name: item.tenant?.name ?? item.tenant_name ?? ''
    }))

    recharges.value = normalizedList
    Object.assign(pagination, response.pagination)

    // 更新统计信息
    const stats = response.statistics
    statistics.totalRecharges = pagination.total
    statistics.pendingCount = stats?.status_counts?.['待处理'] || 0
    statistics.matchedCount = stats?.status_counts?.['已匹配'] || 0
    statistics.todayCount = stats?.today_count || 0
  } catch (error) {
    console.error('请求失败:', error)
    message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const runMatching = async () => {
  matchingLoading.value = true
  try {
    const result = await runMatchingApi()
    message.success(`匹配完成！成功匹配 ${result.matched_count} 笔，成功率 ${result.success_rate}%`)
    fetchRecharges() // 刷新列表
  } catch (error) {
    console.error('匹配失败:', error)
    message.error('匹配失败')
  } finally {
    matchingLoading.value = false
  }
}

const viewDetail = async (recharge: FinanceApi.RechargeRecord) => {
  try {
    const response = await getRechargeDetailApi(recharge.id)
    selectedRecharge.value = {
      ...response.recharge,
      amount: Number(response.recharge.amount ?? 0),
      tenant_name: response.recharge.tenant?.name ?? response.recharge.tenant_name ?? ''
    }
    matchSuggestions.value = response.match_suggestions || []
    showDetail.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    message.error('获取详情失败')
  }
}

const confirmMatch = async (rechargeId: string) => {
  if (!confirm('确认要确认这个匹配吗？')) return

  try {
    await confirmMatchApi(rechargeId)
    message.success('匹配确认成功')
    fetchRecharges()
  } catch (error) {
    console.error('确认失败:', error)
    message.error('确认失败')
  }
}

const confirmMatchDetail = async (rechargeId: string, bankDetailId: string) => {
  if (!confirm('确认要建立这个匹配关系吗？')) return

  try {
    await confirmMatchApi(rechargeId, bankDetailId)
    message.success('匹配确认成功')
    showDetail.value = false
    fetchRecharges()
  } catch (error) {
    console.error('确认失败:', error)
    message.error('确认失败')
  }
}

const handleDetailAfterClose = () => {
  selectedRecharge.value = null
  matchSuggestions.value = []
}

const changePage = (page: number) => {
  if (page < 1 || page > pagination.last_page) return
  filters.page = page
  fetchRecharges()
}

// 表格分页变化处理
const handleTableChange = (paginationInfo: any) => {
  filters.page = paginationInfo.current
  fetchRecharges()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchRecharges()
})
</script>

<style scoped>
/* 如果需要额外的样式可以在这里添加 */
</style>
